
	var Certificate=function(){
	}
	
	Certificate.prototype.subjectDNFilter="crcrfsp";//证书主题DN
	Certificate.prototype.issuerDNFilter="";
	Certificate.prototype.serialNumFilter="";
	Certificate.prototype.cspFilter="";
	Certificate.prototype.p11Name="CFCA_UKEY_P11.dll";//新KEY
	Certificate.prototype.algorithm="SHA-1";//加密算法
	
	var CryptoAgent;
	
	Certificate.prototype.init=function() {
		var dom = document.getElementById("CryptoAgent");
		if(dom){
			dom.parentNode.removeChild(dom);
		}
		try {
			var eDiv = document.createElement("div");
			if (navigator.appName.indexOf("Internet") >= 0 || navigator.appVersion.indexOf("Trident") >= 0) {
				if (window.navigator.cpuClass == "x86") {
					//eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"/common/CFCA/Cryptokit/x86/CryptoKit.Ultimate.x86.cab#version=3,4,0,5\" classid=\"clsid:4C588282-7792-4E16-93CB-9744402E4E98\" ></object>";
					eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"CryptoKit.CRCRFSP.x86.cab#version=3,2,0,1\" classid=\"clsid:336F7652-D7D1-4D92-93D8-1FC3AC5D1B64\" ></object>";
				} else {
					//eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"/common/CFCA/Cryptokit/x64/CryptoKit.Ultimate.x64.cab#version=3,4,0,5\" classid=\"clsid:B2F2D4D4-D808-43B3-B355-B671C0DE15D4\" ></object>";
					eDiv.innerHTML = "<object id=\"CryptoAgent\" codebase=\"CryptoKit.CRCRFSP.x64.cab#version=3,2,0,1\" classid=\"clsid:E5F9A38F-4CE8-49F8-89B1-3B2B720BB39F\" ></object>";
				}
			} else {
				//ignore other browsers, but IE
				//eDiv.innerHTML = "<embed id=\"CryptoAgent\" type=\"application/npCryptoKit.Ultimate.x86\" style=\"height: 0px; width: 0px\">";
				eDiv.innerHTML = "<embed id=\"CryptoAgent\" type=\"application/npCryptoKit.CRCRFSP.x86\" style=\"height: 0px; width: 0px\">";
			}
			document.body.appendChild(eDiv);
			
			CryptoAgent = document.getElementById("CryptoAgent");
			
			console.log("Certificate init finish");
		} catch (e) {
			console.log(e);
			return;
		}
	}
	
	Certificate.prototype.getSignature=function(signatureSourceData){
		return this.getMsgSignature(signatureSourceData);
	}
	
	Certificate.prototype.getMsgSignature=function(sourceData){
		//从控件中选择CFCA证书
		var flag = this.getCFCAMsgSignCertificate();
		var signature = "";
		if(flag){
			try {
				//signature = CryptoAgent.SignMsgPKCS7(signatureSourceData, this.algorithm, false);
				signature = CryptoAgent.SignMsgPKCS7Detached(sourceData, this.algorithm);
			}catch (e) {
				var errorInfo = CryptoAgent.GetLastErrorDesc();
				console.log("getMsgSignature errorInfo="+errorInfo);
			}
		}
		return signature;
	}
	Certificate.prototype.getHashMsgSignature=function(sourceData){
		//从控件中选择CFCA证书
		//var flag = this.getCFCAMsgSignCertificate();
		var signature = "";
		//if(flag){
			try {
				//signature = CryptoAgent.SignMsgPKCS7(signatureSourceData, this.algorithm, false);
				signature = CryptoAgent.SignHashMsgPKCS7Detached(sourceData, this.algorithm);
			}catch (e) {
				var errorInfo = CryptoAgent.GetLastErrorDesc();
				console.log("getHashMsgSignature errorInfo="+errorInfo);
				this.showErrorInfo(errorInfo);
			}
		//}
		return signature;
	}
	
	
	Certificate.prototype.getSubjectDN=function(){
		var subjectDN=CryptoAgent.GetSignCertInfo("SubjectDN");
		return subjectDN;
	}

	Certificate.prototype.check360=function(){
		var result = false;

		console.log("============check360===>");
		for (var key in navigator.plugins) {
			console.log(key+"-"+navigator.plugins[key].filename);
			// np-mswmp.dll只在360浏览器,搜狗下存在
			//internal-nacl-plugin
			if (navigator.plugins[key].filename == 'np-mswmp.dll' || navigator.plugins[key].filename == 'NPSPWRAP.DLL') {
				return !result;
			}
		}
		console.log("============check360===<");
		return result;
	}

	Certificate.prototype.checkEdge=function(){
		var versions = ''
		var arr = /([Ee]dg)\/(\d+)/.exec(navigator.userAgent);
		if(arr){
			versions = arr[2]
		}
		return {
			version: versions
		}
	}
	
	Certificate.prototype.isSupportCFCA=function(){
		var result = false; 
		console.log("============isSupportCFCA===>");
		for (var key in navigator.plugins) {
			console.log(key+"-"+navigator.plugins[key].filename);
			//有这个npCryptoKit.CRCRFSP.x86.dll，就可以调用cfca的插件
	     	if (navigator.plugins[key].filename == 'npCryptoKit.CRCRFSP.x86.dll') {
	     		console.log("============isSupportCFCA===<");
	          	return !result;
	     	}
	 	}
		console.log("============isSupportCFCA===<");
		return result;
	}

	//遨游浏览器
	Certificate.prototype.checkMaxthon=function(){
	    var result = false; 
	    var list = [];
	    for (var key in navigator.plugins) {
	        // 遨游浏览器只有五个一致的plugins
	        if (!!navigator.plugins[key].filename) {
	            list.push(navigator.plugins[key].filename);
	        }
	    }
	    if(list.length == 5){
	        result = true;
	    }else {
	        result = false;
	    }
	    return result;
	}




	//获取当前的浏览器
	Certificate.prototype.getBrowser=function(){
		console.log(">>>>>>>>>> getBrowser start >>>")
		// 获取浏览器 userAgent
		var ua = navigator.userAgent;
		console.log("userAgent="+ua);

		var isOpera = ua.indexOf("Opera") > -1;
		// 是否为 IE
		var isIE = (ua.indexOf('compatible') > -1) && (ua.indexOf('MSIE') > -1) && !isOpera
		var isIE11 = (ua.indexOf('Trident') > -1) && (ua.indexOf("rv:11.0") > -1)
		// 返回结果
		if (isIE11) { return 'IE11'
		} else if (isIE) {
			// 检测是否匹配
			var re = new RegExp('MSIE (\\d+\\.\\d+);')
			re.test(ua)
			// 获取版本
			var ver = parseFloat(RegExp["$1"])
			// 返回结果
			if (ver == 7) { return 'IE7'
			} else if (ver == 8) { return 'IE8'
			} else if (ver == 9) { return 'IE9'
			} else if (ver == 10) { return 'IE10'
			} else { return "IE" }
		}

		// 是否为 Edge
		var isEdge = ua.indexOf("Edg") > -1
		// 返回结果
		if (isEdge) {
			if(this.checkEdge().version>=80) {
				return 'Edge'
			}
		}

		var is360 = this.check360() && (ua.indexOf("Safari") > -1)
		if(is360){return '360浏览器'}

		// 是否为搜狗浏览器
		var isMaxthon = ua.indexOf("SE 2.X") > -1
		// 返回结果
		if (isMaxthon) { return '搜狗浏览器' }



		console.log(">>>>>>>>>> getBrowser end >>>")

		// 都不是
		return ''
	}
	

	//获取消息签名与验签证书
	Certificate.prototype.getCFCAMsgSignCertificate=function(successFn, failFn){
		var bSelectCertResult = false;

		var browser = this.getBrowser()

		console.log(">>> browser="+browser)

		var isSupportCFCA = this.isSupportCFCA();
		console.log("isSupportCFCA="+isSupportCFCA);

		if (browser=='') {
			alert("中国金融认证中心（CFCA）数字证书签名确认方式支持在Edge浏览器（Edge80-最新）、非IE浏览器（360及搜狗中支持NPAPI的浏览器）、IE浏览器（IE10-11）下使用。");
			bSelectCertResult = false;
			parent.ht.closeAllFrameWindow();
		} else if(!isSupportCFCA){
			alert("签章功能无法使用，原因可能为：\n1.浏览器版本不适用，中国金融认证中心（CFCA）数字证书签名确认方式支持在Edge浏览器（Edge80-最新）、非IE浏览器（360及搜狗中支持NPAPI的浏览器）、IE浏览器（IE10-11）下使用；\n2.如浏览器版本适用，可能为当前未安装加载项/数字证书控件，请前往我的园地—数字证书绑定指引页面重新操作绑定流程再进行签章。");
			bSelectCertResult = false;
			parent.ht.closeAllFrameWindow();
		}else{
			try {
				bSelectCertResult = CryptoAgent.SelectCertificate(this.subjectDNFilter,this.issuerDNFilter,this.serialNumFilter,this.cspFilter);
				bSelectCertResult = true;
			}catch (e) {
				var errorInfo = CryptoAgent.GetLastErrorDesc();
				console.log("getCFCAMsgSignCertificate errorInfo="+errorInfo);

				bSelectCertResult = false;
				this.showErrorInfo(errorInfo);
			}
		}

		return bSelectCertResult;

	}
	
	
	Certificate.prototype.showErrorInfo=function(errorInfo){
		if((errorInfo.indexOf("操作已被用户取消") == -1) && errorInfo.indexOf("用户取消选择证书") == -1 ){
        	alert("请检查U盾状态是否正常，如有问题请拨打客服电话：400-009-0001");
        }
		//top.content.baseContent.reload();
		parent.ht.closeAllFrameWindow();
	}
	
	//无证书登录后，插入Key，需给出弹出框,针对上传和确认账款
	Certificate.prototype.getCFCAMsgSignCertificateWithoutCertLogin=function(successFn, failFn){
		 try {
		      var bSelectCertResult = false;
		      bSelectCertResult = CryptoAgent.SelectCertificate(this.subjectDNFilter,this.issuerDNFilter,this.serialNumFilter,this.cspFilter);
		      if (bSelectCertResult) {
		    	  if(successFn){
		    		  successFn();
		    	  }
		      }
		}catch (e) {
			if(failFn){
	  		  failFn();
	  	  	}
		}
	}
	
	//绑定证书专用
	Certificate.prototype.getCFCAMsgSignCertificateForBindingInMyField = function(successFn, failFn){
		 try {
		      var bSelectCertResult = false;
		      bSelectCertResult = CryptoAgent.SelectCertificate(this.subjectDNFilter,this.issuerDNFilter,this.serialNumFilter,this.cspFilter);
		      if (!bSelectCertResult) {
		    	  if(failFn){
		    		  failFn();
		    	  }
		          return;
		      }else{
		    	  if(successFn){
		    		  successFn();
		    	  }
		      }
		}catch (e) {
			console.log("getCFCAMsgSignCertificateForBindingInMyField="+e);
			window.location.href = "/bindCert/showBindingCertError.do";
		}
	}
	
	Certificate.prototype.getSealImage = function(){
		//改为在方法调用前添加选择证书的判断，避免两次弹出提示框。
		//var flag = this.getCFCAMsgSignCertificate();
		var sealImage="";
		//if(flag){
			try {
	            var p11name = this.p11Name;
	            sealImage = CryptoAgent.GetSealImage(p11name);
	            
	            console.log("getSealImage sealImage="+sealImage);
	            
	            var errorInfo = CryptoAgent.GetLastErrorDesc();
				console.log("getSealImage errorInfo 111="+errorInfo);
				
	        } catch (e) {
	        	var errorInfo = CryptoAgent.GetLastErrorDesc();
				console.log("getSealImage errorInfo 222="+errorInfo);
                if(errorInfo.indexOf("操作已被用户取消") != -1){
                	sealImage = -1;
                }else if(errorInfo.indexOf("0xa00718a0") != -1){
                	sealImage = -2;
                }else if(errorInfo.indexOf("0xa00718a1") != -1){
                	sealImage = -2;
                }else if(errorInfo.indexOf("0xa00718a2") != -1){
                	sealImage = -2;
                }else if(errorInfo.indexOf("0xa0071607") != -1){
                	sealImage = "";
                }else{
                	sealImage = -3;
                }
	        }
		//}
        return sealImage;
	}